package com.tanhua.server.service;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.constants.Constants;
import com.tanhua.commons.constants.LogKey;
import com.tanhua.commons.constants.LogType;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.Log;
import com.tanhua.model.domain.User;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Xiao
 * @date 2021/10/21
 */
@Service
@Slf4j
public class UserService {
    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 发送短信验证码
     * @param mobile
     */
    public void sendSms(String mobile) {
        //检查用户冻结状态
        User user = userApi.findByMobile(mobile);
        if (ObjectUtil.isNotEmpty(user)) {
            userFreezeService.checkUserStatus("1", user.getId());
        }
//        String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        log.info("mobile:{}, code:{}", mobile, code);
//        smsTemplate.sendSms(phone, code);
        redisTemplate.opsForValue().set("Login_Code_" + mobile, code, Duration.ofMinutes(5L));
    }

    /**
     * 登陆验证
     * @param mobile
     * @param verificationCode
     * @return
     */
    public Map loginVerification(String mobile, String verificationCode) {
        //从redis中获取验证码
        String codeInRedis = redisTemplate.opsForValue().get("Login_Code_" + mobile);
        //判断验证码是否存在、和redis中的验证码是否一致
        //如果不一致或不存在，抛出异常
        if (StringUtils.isEmpty(verificationCode) || !verificationCode.equals(codeInRedis)) {
//            throw new RuntimeException("验证码有误！");
            throw new BusinessException(ErrorResult.loginError());
        }
        //如果验证码正确，通过手机号查询用户是否在数据库中存在,删除redis中的缓存
        redisTemplate.delete("Login_Code_" + mobile);
        User user = userApi.findByMobile(mobile);
        boolean isNew = false;
        String type = LogType.USER_LOGIN;
        //如果不存在，添加新用户
        if (user == null) {
            type = LogType.USER_REGISTER;
            user = new User();
            user.setMobile(mobile);
            /*user.setCreated(new Date());
            user.setUpdated(new Date());*/
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.saveUser(user);
            user.setId(userId);
            isNew = true;
            //注册环信账号
            String hxUser = Constants.HX_USER_PREFIX + user.getId();
            String hxPassword = Constants.INIT_PASSWORD;
            Boolean created = huanXinTemplate.createUser(hxUser, hxPassword);
            if (created) {
                //存储环信账号信息到user表
                user.setHxUser(hxUser);
                user.setHxPassword(hxPassword);
                userApi.updateById(user);
            }
        }
        //通过amqp发送日志消息
        /*Long userId = user.getId();
        String logTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String message = JSON.toJSONString(Log.init(userId, logTime, type, null));
        try {
            amqpTemplate.convertAndSend("tanhua.log.exchange",
                    "log.user",message);
        } catch (AmqpException e) {
            e.printStackTrace();
        }*/
        mqMessageService.sendLogMessage(user.getId(), type, LogKey.USER, null);
        //通过JWT生成Token(存入id和mobile)
        Map tokenMap = new HashMap<>();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile", mobile);
        String token = JwtUtils.getToken(tokenMap);
        //构造返回值
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);
        return retMap;
    }
}
